const app = getApp()

var util = require("../../../../common/util/util");

Page({
    data: {
        war : false ,
        statusBar : '',
        customBar : '',
        my : '' ,
        id : '' ,
        pay : false ,
        data : {} ,
        need : false ,
        xInfoNeed : false ,
        needknow : false
    },

    onLoad : function (opt) {
        wx.showLoading({
            title: '加载中',
        })
        let id = opt.id
        this.setData({
            id : id ,
            pid : id
        })
    },

    onShow : function () {
        let id = this.data.id
        this.xInit(id)
        this.xSystem()
        this.xCantBuy()
        this.xGetDoc()
    },

    xUser : function () {
        if(app.globalData.userInfo){
            this.setData({
                hasUserInfo: true,
                userInfo: app.globalData.userInfo
            })
        }
        wx.cloud.callFunction({
            name:"user",
            data:{
                action:"detail"
            },
            success: (res) => {
                let data = res.result
                that.setData({
                    my: data
                })
            }
        })
    },

    xInit : function (id) {
        let that = this
        wx.cloud.callFunction({
            name: "product",
            data: {
                action: "detail",
                product_id: id
            },
        }).then( res => {
            let data = res.result
            console.log(data)
            that.setData({
                data : data
            })
            wx.hideLoading()
        })
    },

    xPhoneNumber : function (e) {
        wx.showLoading({
            title: '加载中',
        })
        let that = this
        let war = that.data.war
        wx.cloud.callFunction({
            name: 'user',
            data: {
                action: 'getPhone',
                cloudID: e.detail.cloudID
            },
            success : res => {
                wx.hideLoading({})
                if(res.result.phoneNumber !== undefined){
                    that.setData({
                        war : true
                    })
                    let form = {
                        phone_number : res.result.phoneNumber
                    }
                    wx.cloud.callFunction({
                        name: "user",
                        data: {
                            action: "edit",
                            formdata: form
                        }
                    }).then(res => {
                        wx.hideLoading()
                    })
                }else{
                    that.setData({
                        war : false
                    })
                }
            },
            fail : err => {
                wx.showToast({
                    title: '授权失败',
                    icon: 'none'
                })
            }
        })
    },

    // 刘海屏监听
    xSystem: function(){
        let that = this
        wx.getSystemInfo({
            success: (e) => {
                let custom = wx.getMenuButtonBoundingClientRect();
                that.setData({
                    statusBar : e.statusBarHeight,
                    customBar : custom.bottom + custom.top - e.statusBarHeight
                })
            }
        })
    },

    // 返回上一页
    xBack: function () {
        wx.navigateBack({
            delta: 1 ,
            fail : () => {
                wx.switchTab({
                    url: '/pages/navigation/index/index',
                })
            }
        })
    },

    // 购买
    buyed: async function(e){
        let that = this
        that.paymentNext()
        // if (!that.data.war) {
        //     wx.showModal({
        //         title: '提示',
        //         content: '请先阅读并确认知情同意书',
        //         showCancel: false,
        //         complete (res) {
        //             wx.pageScrollTo({
        //                 selector:"#consent-link"
        //             })
        //         }
        //     })
        // }else{
        //     if(that.data.my.isUsed === undefined){
        //         that.paymentNext()
        //     }
        //     if(!that.data.isUsed && that.data.my.isUsed !== undefined){
        //         that.paymentNext()
        //     }
        // }
    },
    paymentNext: async function(){
        let that = this
        wx.showLoading({
            title: '支付准备中',
        })
        let currentTime = new Date()
        let year = currentTime.getFullYear
        let m = currentTime.getMonth
        let day = currentTime.getDay
        let timestamp = ""+(new Date()).getTime()
        console.log(that.data.data)
        let product = that.data.data
        that.prepay(product.name, product.price, timestamp, product._id)
    },
    prepay: function(productName, price, timestamp,productId){
        let that = this
        wx.cloud.callFunction({
            name : 'payment',
            data: {
                action: 'prepay',
                productName: productName,//商品名称
                price: price, //价格that.data.seriesLessonsData.price
                timestamp: timestamp,
                productId: productId,
                planId: that.data.data.plan_id
            },
            success(res) {
                wx.hideLoading()
                let payData = res.result
                let timeStamp = payData.payment.timeStamp
                let totalFee = price
                that.pay(payData.payment, totalFee, timeStamp, productId)
            }
        })
    },
    pay: function(payData, totalFee, timeStamp, productId){
        let that = this
        let id = that.data.id
        wx.requestPayment({
            timeStamp: payData.timeStamp,
            nonceStr: payData.nonceStr,
            package: payData.package, //统一下单接口返回的 prepay_id 格式如：prepay_id=***
            signType: 'MD5',
            paySign: payData.paySign, //签名
            success(res) {
                wx.showModal({
                    title: '下单成功',
                    content: '咨询师会在1天内与您确认时间，请保持手机畅通',
                    showCancel: false,
                    // cancelText: "晚点再说" ,
                    confirmText: "确定" ,
                    success: res => {
                        if (res.confirm) {
                            wx.navigateBack({
                                delta: -1,
                            })
                        }
                    }
                })
            },
            fail(res) {
                console.log("支付失败", res)
            },
            complete(res) {
                // let id = that.data.id
                // // that.init(id)
                // // let progress = that.data.data.additional.diagnosis_treatment_status
                // // if(progress === 1){
                // //     let id = 'all'
                // //     let week = progress
                // //     wx.navigateTo({
                // //         url: '/svc/pages/evl/detail/index?id=' + id + '&week=' + week + '&okey=other' + '&turn=true',
                // //     })
                // // }else{
                // //     that.xInit(id)
                // // }
                console.log("支付完成,complete res :", res)
            }
        })
    },

    paynow : function () {
        let that = this
        let pay = that.data.pay
        let war = that.data.war
        console.log(war)
        console.log(pay)
        if(!war){
            wx.showToast({
                title: '请先阅读协议',
                icon: 'none' ,
                success: () => {
                    wx.createSelectorQuery().select('#ownContainer').boundingClientRect(function (rect) {
                        wx.pageScrollTo({
                            scrollTop: rect.bottom
                        })
                    }).exec()
                }
            })
        }else{
            wx.requestSubscribeMessage({
                tmplIds: [
                    "s-Mq0IcYoqL6yFi0ttPSTngYneBzFi6O7NKAVRWT0pM",
                    "TBmwFgapJW30qV3VfL517MUqLvbyftvQhNWD6rWideI",
                    "P98CB28Vu8VCLhsS1mujfeRAJVSKNCHkgfPGqfR7g-E"
                ],
                success: (res) => {
                    if (res['s-Mq0IcYoqL6yFi0ttPSTngYneBzFi6O7NKAVRWT0pM'] === 'accept') {
                        wx.cloud.callFunction({
                            name: 'message_subscribe',
                            data: {
                                action: "add_subscribe",
                                dataObj: {
                                    templateid: "s-Mq0IcYoqL6yFi0ttPSTngYneBzFi6O7NKAVRWT0pM",
                                    subscribe_status_string: "accept"
                                }
                            }
                        }).then(res => {
                            wx.showToast({
                                title: '订阅成功',
                                icon: 'none',
                                duration: 1000,
                            })
                        })
                    }
                },
                fail() { },
                complete() {
                    that.setData({
                        pay : true ,
                        need : false ,
                    })
                }
            })
        }
    },

    xCantBuy : function () {
        let that = this
        let id = that.data.id
        wx.cloud.callFunction({
            name: 'digital_therapy',
            data: {
                action: "is_audit_fail",
                _id: id
            }
        }).then(res => {
            console.log("是否可以购买:", res)
        })
    },

    xToMyInfo : function () {
        let that = this
        let progress = that.data.data.additional.diagnosis_treatment_status
        if(progress === 1 || progress === 2){
            let id = 'all'
            wx.navigateTo({
                url: '/svc/pages/evl/detail/index?id=' + id + '&week=' + progress + '&okey=other' + '&turn=true',
            })
        }
    },

    xNeedKnow : function () {
        let that = this
        let need = that.data.need
        console.log(need)
        that.setData({
            pay : true ,
            need : true
        })
    },

    xGetDoc : function () {
        let that = this
        wx.cloud.callFunction({
            name : 'user' ,
            data : {
                action : 'detail'
            }
        }).then( res => {
            console.log('用户数据' , res.result)
            that.setData({
                doc : res.result.consultation_teacher_info[0] ,
                uava : res.result.avatarUrl ,
                id : res.result.user_id
            })
            let user = res.result
            if(user.real_name == '' || user.real_name == undefined || user.real_name == null){
                that.setData({
                    xInfoNeed : true
                })
            }
            if(user.sex == '' || user.sex == undefined){
                that.setData({
                    xInfoNeed : true
                })
            }
            if(user.education == '' || user.education == undefined){
                that.setData({
                    xInfoNeed : true
                })
            }
            if(user.birthday == '' || user.birthday == undefined){
                that.setData({
                    xInfoNeed : true
                })
            }
            if(user.other_drugs == '' || user.other_drugs == undefined){
                that.setData({
                    xInfoNeed : true
                })
            }
        })
    },
})